<?php

class Itc_View_Helper_HeadScriptProxy extends Zend_View_Helper_HeadScript{
    /**
     * Registry key for placeholder
     * @var string
     */
    protected $_regKey = 'Itc_View_Helper_HeadScriptProxy';
    
    /**
     * Proxied items
     * @var array
     */
    protected $proxyItems  = array();
    
    protected $proxySource = '';
    
	/**
	 * Instance of build object
	 * @var Itc_Build
	 */
	protected $compressor;

	public function __construct()
	{
		$this->compressor = new Itc_Compressor(Zend_Registry::get('Config')->headScript);
		parent::__construct();
	}
    
        /**
     * Return headScriptProxy object
     *
     * Returns headScriptProxy helper object.
     *
     * @return Itc_View_Helper_HeadScriptProxy
     */
    public function headScriptProxy() 
    {
        return $this;
    }
    
    /**
     * Overrides method toString() of parent class
     * (non-PHPdoc)
     * @see library/Zend/View/Helper/Zend_View_Helper_HeadScript#toString($indent)
     */
    public function toString($indent = null)
    {
		//return parent::toString($indent);
    	$items = array();
		$indexes = array();
		$this->getContainer()->ksort();
		foreach ($this as $k=>$item) {
			$this->proxyItems[] = $item->attributes['src'];
			$indexes[] = $k;
		}
		if (count($this->proxyItems) > 0){
			$this->compressor->setFiles($this->proxyItems);
			try {
				$this->compressor->compresed('js');
				$mergedItem = $this->createData('text/javascript', array('src' => $this->compressor->getFileName(true, false)));
				$this->append($mergedItem);
				for ($i=0, $n=count($indexes); $i<$n; $i++) {
					unset($this[$indexes[$i]]);
				}
			} catch (Exception $e) {
				
			}
		}
		return parent::toString($indent);
    }

    /**
     * Remove file
     * @param $src
     */
	public function removeFile($src)
	{
		$container = $this->getContainer();
		$rem_index = -1;
		foreach ($container as $k=>$item) {
			if ($item->attributes['src'] == $src){
				$rem_index = $k;
			}
		}
		if ($rem_index > -1){
			unset($this[$rem_index]);
		}
	}
}